#include "paneltagsummary.h"
#include "main.h"
#include "pm/manager.h"
#include "pm/summary.h"
#include <boost/foreach.hpp>

PanelTagSummary::PanelTagSummary(wxWindow* parent)
: PanelTagSummaryGui(parent)
{
	m_listTag->InsertColumn(COL_NAME,    _("Tag name"));
	m_listTag->InsertColumn(COL_PERCENT, _("Percentage"), wxLIST_FORMAT_RIGHT);
	
	wxTheApp->Connect(pmEVT_PROJECT_LOADED, wxCommandEventHandler(PanelTagSummary::OnProjectLoaded), NULL, this);
	
	pmConnectNotify(pmEVT_WORK_REQUEST_ADDED,   PanelTagSummary::OnTagSummaryChanged);
	pmConnectNotify(pmEVT_WORK_REQUEST_UPDATED, PanelTagSummary::OnTagSummaryChanged);
	pmConnectNotify(pmEVT_WORK_REQUEST_REMOVED, PanelTagSummary::OnTagSummaryChanged);
	
	pmConnectNotify(pmEVT_COST_ADDED,   PanelTagSummary::OnTagSummaryChanged);
	pmConnectNotify(pmEVT_COST_UPDATED, PanelTagSummary::OnTagSummaryChanged);
	pmConnectNotify(pmEVT_COST_REMOVED, PanelTagSummary::OnTagSummaryChanged);
	
	pmConnectNotify(pmEVT_TAG_ADDED,   PanelTagSummary::OnTagSummaryChanged);
	pmConnectNotify(pmEVT_TAG_UPDATED, PanelTagSummary::OnTagSummaryChanged);
	pmConnectNotify(pmEVT_TAG_REMOVED, PanelTagSummary::OnTagSummaryChanged);
	
	pmConnectNotify(pmEVT_TASK_ADDED,   PanelTagSummary::OnTagSummaryChanged);
	pmConnectNotify(pmEVT_TASK_UPDATED, PanelTagSummary::OnTagSummaryChanged);
	pmConnectNotify(pmEVT_TASK_REMOVED, PanelTagSummary::OnTagSummaryChanged);
}

void PanelTagSummary::ReloadTagSummary()
{
	m_listTag->DeleteAllItems();
	
	db::ID idProject = wxGetApp().GetActiveProject();
	
	pm::GetSummaryByProject critSummary(idProject);
	pm::select(critSummary);
	
	pm::GetTagSummary critTagSummary(idProject);
	pm::select(critTagSummary);
	BOOST_FOREACH(const pm::TagSummary& tagSummary, critTagSummary.m_result) {
		AddTagSummary( Summary(tagSummary, critSummary.m_result.estimation()) );
	}
}

void PanelTagSummary::AddTagSummary(const Summary& summary)
{
	long item = m_listTag->InsertItem(m_listTag->GetItemCount(), wxEmptyString);
	SetTagSummary(item, summary);
}

void PanelTagSummary::SetTagSummary(long item, const Summary& summary)
{
	m_listTag->SetItem(item, COL_NAME,    summary.name());
	m_listTag->SetItem(item, COL_PERCENT, wxString::Format(wxT("%.1f %%"), summary.percent()));
}

void PanelTagSummary::OnProjectLoaded(wxCommandEvent& event)
{
	event.Skip();
	ReloadTagSummary();
}

void PanelTagSummary::OnTagSummaryChanged(wxNotifyEvent& event)
{
	event.Skip();
	ReloadTagSummary();
}
